package com.monco.listener;

import com.monco.config.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

/**
 * @Auther: monco
 * @Date: 2019/7/11 15:01
 * @Description: 监听过期key回调方法
 */
@Slf4j
@Component
public class RedisMessageListener implements MessageListener {

    @Autowired
    private RedisService redisService;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        log.info("监听过期key开始》》》");
        String channel = new String(message.getChannel());
        String str = (String) redisService.getRedisTemplate().getValueSerializer().deserialize(message.getBody());
        log.info(str);
        log.info("此任务" + str + "已过期" + "通道为" + channel);
        String[] strings = str.split("-");
        String queueName = strings[0];
        log.info("删除过期任务" + str);
        redisService.lLeftPop(queueName);
        if (redisService.lGetListSize(queueName) != 0) {
            String dataKey = (String) redisService.lGetIndex(queueName, 0);
            String content = (String) redisService.get(dataKey);
            log.info("获得下一次任务" + dataKey + "的内容" + content);
            redisService.expire(dataKey, 30);
        }
    }
}
